// 130.被围绕的区域
package Leetcode_Second_Brush;

public class Solution130 {
    public void solve(char[][] board) {
        if (board == null || board.length == 0) {
            return;
        }

        int rows = board.length;
        int cols = board[0].length;

        // Mark the border-connected 'O's
        for (int i = 0; i < rows; i++) {
            DFS(board, i, 0);
            DFS(board, i, cols - 1);
        }
        for (int j = 0; j < cols; j++) {
            DFS(board, 0, j);
            DFS(board, rows - 1, j);
        }

        // Flip remaining 'O' to 'X' and 'A' back to 'O'
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                } else if (board[i][j] == 'A') {
                    board[i][j] = 'O';
                }
            }
        }
    }

    private void DFS(char[][] board, int i, int j) {
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != 'O') {
            return;
        }

        board[i][j] = 'A';

        DFS(board, i - 1, j);
        DFS(board, i + 1, j);
        DFS(board, i, j - 1);
        DFS(board, i, j + 1);
    }

}
